package com.xk.page.service;

import com.hy.item.pojo.*;
import com.xk.page.client.BrandClient;
import com.xk.page.client.CategoryClient;
import com.xk.page.client.GoodsClient;
import com.xk.page.client.SpecificationClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private SpecificationClient specificationClient;
    @Autowired
    private TemplateEngine templateEngine;

    public Map<String,Object> toItemPage(Long id) {
        //查询spu中的信息
        Spu spu = goodsClient.querySpuById(id);
        //查询skus
        List<Sku> skus = goodsClient.querySkuById(id);
        //查询detail(spu详情)
        SpuDetail detail = goodsClient.queryDetailById(id);
        //查询brand
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        //查询商品分类
        List<Category>  categories= categoryClient.queryCategoryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //查询规格组及组内参数,在组中扩展了规格参数
        List<SpecGroup> specs = specificationClient.queryListByCid(spu.getCid3());
        Map<String, Object> map = new HashMap<>();
        map.put("spu",spu);
        map.put("title",spu.getTitle());
        map.put("sub_title",spu.getSubTitle());
        map.put("skus",skus);
        map.put("detail",detail);
        map.put("brand",brand);
        map.put("categories",categories);
        map.put("specs",specs);
        return map;
    }

    /**
     * 实现页面静态化
     * @param spuId
     * @throws FileNotFoundException
     */
    public void createHtml(Long spuId) throws FileNotFoundException {
        //上下文
        Context context = new Context();
        context.setVariables(toItemPage(spuId));
        //输出流
        File file = new File("F:\\yyyy",spuId+".html");
        //判断文件是否存在，如果存在就删除，然后重新生成
        if (file.exists()){
            file.delete();
        }
        PrintWriter writer = new PrintWriter(file);
        //生成html
        templateEngine.process("item",context,writer);
    }
}
